const db = require('../db/dbconfig');

// 获取所有用户信息
const getusers = async(req, res) => {
    let { keyword, pagenum, pagesize } = req.query;
    let sql = 'select * from user',
        data = null,
        msg = '请求成功！',
        status = 200,
        total = 0
    let count_sql = `select count(*) 'total' from user`
    try {
        if (pagenum && pagesize) {
            if (keyword) {
                sql += ` where username like '%${keyword}%'`
                count_sql += ` where username like '%${keyword}%'`
            }
            sql += ` limit ${(pagenum-1) * pagesize},${pagesize}`
            data = await db.sqlconnection(sql)
            const count_result = await db.sqlconnection(count_sql)
            total = count_result[0].total
        } else {
            status = 400
            msg = '参数必填'
        }
    } catch (error) {
        msg = `请求发生错误:${error}`
        status = 400
    } finally {
        res.status(status).send({
            data,
            total,
            meta: {
                status,
                msg
            }
        })
    }
}



// 用户登录
const userLogin = async(req, res) => {
    let { username, password } = req.body,
        sql = `select * from user where username = ?`,
        data = null,
        msg = '登录成功!',
        status = 200
    if (username && password) { // 判断用户输入的两个参数是否为真
        data = await db.sqlconnection(sql, [username]);
        status = 400
        console.log(status);
        if (data.length > 0) {
            // 如果data>0，说明数据库中有该用户的数据，但只能说明存在这个用户，密码对不对不知道
            status = 200
            if (password !== data[0].password) {
                // 判断用户输入的密码和数据库中data返回的密码是否相同，如果相同就登陆成功
                data = null
                msg = '密码错误,请检查'
                status = 400
            }
        } else {
            msg = '账号不存在，请先注册'
            data = null
            status = 400
        }
    } else {
        msg = '参数必填'
        status = 400
    }
    res.status(status).send({
        data,
        meta: {
            msg,
            status
        }
    })
}

// 用户注册(添加用户)
const registeruser = async(req, res) => {
    let { username, password, gender, email, mobile } = req.body,
        date = new Date(),
        status = 200
    regtime = `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
    insert_sql = `insert into user (username,password,gender,email,mobile,regtime)
        values ('${username}','${password}','${gender?gender:0}','${email?email:null}','${mobile?mobile:null}','${regtime}')`,
        msg = '注册成功',
        data = null
    if (username && password) { // 判断输入是否为空
        let select_sql = `select * from user where username = '${username}'`
        const result = await db.sqlconnection(select_sql);
        if (result.length === 0) { // 判断用户名是否已经被注册
            let add_result = await db.sqlconnection(insert_sql)
            if (add_result.affectedRows <= 0) { // 判断新增sql语句是否添加成功
                msg = '注册失败'
                status = 400
            }
        } else {
            status = 400
            msg = '账号已存在，请更换账号注册'
        }
    } else {
        status = 400
        msg = '参数必填'
    }
    res.status(status).send({
        meta: {
            msg,
            status
        }
    })
}


// 删除用户信息
const deleteuser = async(req, res) => {
    let { id } = req.query,
        sql = `delete from user where id = '${id}'`,
        msg = '删除信息成功',
        status = 200;
    try {
        const result = await db.sqlconnection(sql)
        if (result.affectedRows <= 0) { // 根据受影响行数来判断是否删除成功
            status = 400
            msg = '删除用户信息失败'
        }
    } catch (error) {
        status = 400
        msg = `执行出错`
    } finally {
        res.status(status).send({
            meta: {
                msg,
                status
            }
        })
    }
}

// 修改用户信息
const updateuser = async(req, res) => {
    let { gender, email, mobile, id } = req.body,
        status = 200
    update_sql = `update user set gender = ?,email = ?,mobile = ? where id = ?`,
        msg = '修改信息成功!'
    if (id && id > 0) {
        const result = await db.sqlconnection(update_sql, [gender, email, mobile, id]);
        if (result.affectedRows <= 0) {
            status = 400
            msg = '信息修改失败!'
        }
    } else {
        status = 400
        msg = '参数必填'
    }
    res.status(status).send({
        meta: {
            status,
            msg
        }
    })
}

// 修改用户密码
const updatepassword = async(req, res) => {
    let { oldpassword, newpassword, id } = req.body,
        status = 200
    sql = `update user set password = ? where id = ?`
    msg = '修改密码成功!'
    if (oldpassword && newpassword && id && id > 0) {
        select_sql = `select * from user where id = ?`
        const select_result = await db.sqlconnection(select_sql, [id])
        if (select_result[0].password === oldpassword) {
            const update_result = await db.sqlconnection(sql, [newpassword, id]);
            if (update_result.affectedRows <= 0) {
                status = 400
                msg = `密码修改失败!`
            }
        } else {
            status = 400
            msg = '原密码输入错误!'
        }
    } else {
        status = 400
        msg = '参数必填'
    }
    res.status(status).send({
        meta: {
            status,
            msg
        }
    })
}


// 当前端点击编辑按钮时，查询单个的用户信息

const select_oneuser = async(req, res) => {
    let { id } = req.query,
        status = 200,
        msg = '查询成功',
        sql = `select * from user where id = ?`,
        data = null
    if (id && id > 0) {
        data = await db.sqlconnection(sql, [id])
    } else {
        msg = '参数必填'
    }
    res.status(status).send({
        data,
        meta: {
            msg,
            status
        }
    })
}

module.exports = {
    getusers,
    userLogin,
    registeruser,
    deleteuser,
    updatepassword,
    updateuser,
    select_oneuser
}